package com.fits.auth.api.dto;

import cn.hutool.core.collection.CollUtil;
import com.fits.starter.common.security.LoginUserDTO;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class SecurityUser implements UserDetails {
    @ApiModelProperty("主键id")
    private Integer id;
    @ApiModelProperty("用户名")
    private String username;
    @ApiModelProperty("密码")
    private String password;
    @ApiModelProperty("是否启用")
    private Boolean enabled;
    @ApiModelProperty("客户端")
    private String clientId;
    @ApiModelProperty("角色ids")
    private List<Integer> roleidsList;
    @ApiModelProperty("角色名称")
    private List<String> roleNameList;
    @ApiModelProperty("权限")
    private Collection<SimpleGrantedAuthority> authorities;
    @ApiModelProperty("部门ids")
    private List<Integer> deptList;

    public SecurityUser(LoginUserDTO dto) {
        this.setUsername(dto.getUserName());
        this.setPassword(dto.getPassword());
        this.setId(dto.getId());
        this.setEnabled(true);
        this.setRoleidsList(dto.getRoleIdList());
        this.setRoleNameList(dto.getRoleNameList());
        this.setDeptList(dto.getDeptList());
        //角色绑定
        if (CollUtil.isNotEmpty(dto.getRoleIdList())) {
            List<SimpleGrantedAuthority> authoritiesList = dto.getAuthorities().stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
            this.setAuthorities(authoritiesList);
        }
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
